getters, setters and instanceOf in JavaScript
1. Getters
A getter is a special method that looks like a property but actually runs a function when accessed.
Used to retrieve values in a controlled way.
Example of Getters:-
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Getter method
get fullName() {
return this.firstName + " " + this.lastName;
}
}
let person1 = new Person("John", "Doe");
console.log(person1.fullName); // John Doe (looks like a property, but runs a method)
Explanation:-
get fullName() makes fullName look like a property but it runs a function.
When person1.fullName is accessed, it computes "John Doe" dynamically.
Getters are useful for derived/computed properties (like full name from first + last)
2. Setters
A setter is used to set or update a property’s value in a controlled way.
Useful when you want to add validation or modify the value before saving.
Example of Getters:-
class Person {
constructor(name) {
this._name = name; // convention: _ means private-like property
}
// Getter
get name() {
return this._name;
}
// Setter
set name(newName) {
if (newName.length > 0) {
this._name = newName;
} else {
console.log("Name cannot be empty!");
}
}
}
let person2 = new Person("Alice");
console.log(person2.name); // Alice
person2.name = "Bob"; // calls setter
console.log(person2.name); // Bob
person2.name = ""; // Invalid, setter blocks it
// Output: Name cannot be empty!
Explanation:-
set name(newName) allows controlled modification of _name.
If you try to set "", the setter blocks it with a validation message.
Setters are great for data validation and restrictions before updating values.
3. instanceof Operator
Used to check whether an object is an instance of a particular class (or its parent in the prototype chain).
Example of Getters:-
class Vehicle {}
class Car extends Vehicle {}
let myCar = new Car();
console.log(myCar instanceof Car); // true
console.log(myCar instanceof Vehicle); // true (because Car extends Vehicle)
console.log(myCar instanceof Object); // true (all classes extend Object in JS)
console.log(myCar instanceof Array); // false
Explanation:-
instanceof checks if an object belongs to a class or its inheritance chain.
myCar instanceof Car → true because myCar was created using Car.
myCar instanceof Vehicle → true since Car inherits from Vehicle.
All classes in JS inherit from Object, so instanceof Object → true.
Returns false if the object doesn’t belong to that class (like Array).